<script setup lang="ts">
import { ref, reactive } from "vue"
import { type FormRules, ElMessage } from 'element-plus';
import { addArticleCategoryService, updateArticleCategoryService } from "@/api/category";
import { categoryModel } from "@/models/article";
// 分类表单校验规则
const rules = reactive<FormRules<typeof categoryModel>>({
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
  ],
  categoryAlias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
  ]
})
// 确认添加文章分类
const addCategory = async () => {
  try {
    const result = await addArticleCategoryService(categoryModel.value)
    ElMessage.success("添加成功")
    // 重新获取分类列表
    props.getCategory()
    emits('update-dialogVisible', false)
  }
  catch (err) {
    console.log(err);
  }
}
// 确认编辑文章分类
const updateCategory = async () => {
  try {
    const result = await updateArticleCategoryService(categoryModel.value)
    console.log(result);
    ElMessage.success("修改成功")
    // 重新获取分类列表
    props.getCategory()
    emits('update-dialogVisible', false)
  } catch (err) {
    console.log(err);
    ElMessage.error("修改失败")
  }

}

// 接受父传递的数据
const props = defineProps(['dialogVisible', 'getCategory', 'title'])
const dialogVisible = ref(props.dialogVisible);
// 自定义emit事件(子传父)
const emits = defineEmits(['update-dialogVisible'])
</script>
<template>
  <el-dialog :title=props.title width="30%">
    <el-form :model="categoryModel" :rules="rules" label-width="100px" style="padding-right: 30px">
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="categoryModel.categoryName" minlength="1" maxlength="10"></el-input>
      </el-form-item>
      <el-form-item label="分类别名" prop="categoryAlias">
        <el-input v-model="categoryModel.categoryAlias" minlength="1" maxlength="15"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="emits('update-dialogVisible', false)">取消</el-button>
        <el-button type="primary" @click="props.title == '编辑分类' ? updateCategory() : addCategory()"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss"></style>